package br.mendonca.gmgraphlib;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Scanner;

import br.mendonca.gmgraphlib.exception.EmptyFileException;
import br.mendonca.gmgraphlib.exception.InvalidEdgeException;

/**
 * @author Gabriel Mendonça - gabrielgmendonca@gmail.com
 *
 */
public class GraphUtil {
	
	/**
	 * Creates a graph from a source file.
	 * @param fileName name of the file that will be readed.
	 * @param graphType TODO
	 * @throws InvalidEdgeException 
	 */
	public static Graph loadGraph(String fileName, String graphType, int dataStructure) throws EmptyFileException, InvalidEdgeException {
		Scanner scanner = null;
		
		try {
			scanner = new Scanner(new File(fileName));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return loadGraph(scanner, graphType, dataStructure);
	}
	
	/**
	 * Creates a graph from a source file.
	 * @param graphType TODO
	 * @param dataStructure TODO
	 * @param reader
	 */
	public static Graph loadGraph(Scanner scanner, String graphType, int dataStructure) throws EmptyFileException, InvalidEdgeException {		
		try {
			Integer numberOfVertices = new Integer(scanner.nextLine());
			Graph graph = Graph.getInstance(graphType, numberOfVertices, dataStructure);
			
			while (scanner.hasNextLine()) {
				graph.addEdge(scanner.nextInt(), scanner.nextInt());
			}
			
			return graph;
			
		} catch (NoSuchElementException e) {
			throw new EmptyFileException();
			
		} finally {
			scanner.close();
		}
	}

	/**
	 * Writes the basic informations of a graph in a file.
	 * @param graph the graph that will be saved.
	 * @param path
	 * @throws IOException 
	 */
	public static void saveGraph(Graph graph, String path) throws IOException {		
		File file = new File(path);
		FileWriter fileWriter = new FileWriter(file);
		BufferedWriter writer = new BufferedWriter(fileWriter);

		try {
			writer.write(String.valueOf(graph.getVertexList().size()));
			
			EdgeList edgeList = graph.getEdgeList();
			while (edgeList.hasNext()) {
				Edge edge = edgeList.next();
				
				writer.newLine();
				writer.write(edge.toString());
			}
			
		} finally {
			writer.close();
		}
	}

	
}
